#!/bin/bash

# 加载 .env 文件中的变量
if [ -f ".env" ]; then
  source .env
  echo "已加载 .env 文件"
else
  echo "未找到 .env 文件"
  exit 1
fi

# 检查 Docker 镜像是否存在
check_image() {
  if ! docker inspect $1 > /dev/null 2>&1; then
    return 1
  else
    return 0
  fi
}

# 确保 images 目录存在
mkdir -p images

# 导出应用镜像并压缩
export_image() {
  local image_name=$1
  local file_name="$(basename ${image_name} | tr ':' '_').tar.gz"
  local file_path="images/${file_name}"

  if check_image "${image_name}"; then
    echo "正在导出镜像 ${image_name}..."
    docker save "${image_name}" | gzip > "${file_path}"
    if [ $? -ne 0 ]; then
      echo "导出镜像失败: ${image_name}"
      return 1
    fi
    echo "镜像 ${image_name} 已成功导出并压缩到 ${file_path}"
  else
    echo "镜像 ${image_name} 不存在"
    return 1
  fi
}

# 导入镜像
import_image() {
  local file_path=$1
  local image_name=$(basename "${file_path}" .tar.gz | tr '_' ':')

  if [ -f "${file_path}" ]; then
    echo "正在导入镜像 ${file_path}..."
    docker load -i "${file_path}"
    if [ $? -ne 0 ]; then
      echo "导入镜像失败: ${file_path}"
      return 1
    fi
    echo "镜像 ${file_path} 已成功导入"
  else
    echo "文件 ${file_path} 不存在"
    return 1
  fi
}

# 主循环
while true; do
  echo "请选择操作:"
  echo "1. 导出镜像"
  echo "2. 导入镜像"
  echo "3. 退出"
  read -p "请输入选项 (1/2/3): " choice

  case $choice in
    1)
      # 导出镜像
      for img in "${APP_IMAGE}" "${MIGRATOR_IMAGE}"; do
        export_image "${img}"
      done
      ;;
    2)
      # 导入镜像
      for file in $(find images -name "*.tar.gz"); do
        import_image "${file}"
      done
      ;;
    3)
      # 退出
      echo "退出程序"
      break
      ;;
    *)
      echo "无效选项，请重新输入"
      read -p "按任意键继续..."
      ;;
  esac
done